/*
 * Copyright (C) 2010 Fred Barrie This program is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version. This program is distributed
 * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details. You should have received
 * a copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
package org.aergia.vinny.database.util;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Logger;

/**
 * @author fred
 */
public final class DerbyUtil {

	public static void backUpDatabase(final Connection conn) throws SQLException {
		// Get today's date as a string:
		final java.text.SimpleDateFormat todaysDate = new java.text.SimpleDateFormat("yyyy-MM-dd");
		final String backupdirectory = "../backups/" + todaysDate.format(java.util.Calendar.getInstance().getTime());

		final CallableStatement cs = conn.prepareCall("CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)");
		cs.setString(1, backupdirectory);
		cs.execute();
		cs.close();
		Logger.getLogger(DerbyUtil.class.getName()).info("backed up database to " + backupdirectory);
	}

	public static void cleanDatabase(final Connection conn) throws SQLException {

		final String[] tableNames = { "Card", "Location", "OperatingHours", "Organization", "Scan", "Service", "Skill", "SkillRate", "VinnyOption",
				"VinnyRole", "VinnyUser", "VinnyUser_VinnyRole", "Volunteer", "Volunteer_Skill", "VolunteerGroup" };

		for (final String tableName : tableNames) {
			final PreparedStatement statement = conn.prepareStatement("delete from " + tableName);
			statement.executeUpdate();
		}
		conn.commit();
	}

	private DerbyUtil() {
		// empty
	}
}
